package com.book.ordermanagement;

 import com.book.ordermanagement.state.OrderStateChangeAction;
 import com.book.ordermanagement.state.OrderStateConstant;
 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.persist.RepositoryStateMachinePersist;
import org.springframework.statemachine.redis.RedisStateMachineContextRepository;
import org.springframework.statemachine.redis.RedisStateMachinePersister;

 import java.util.Arrays;
 import java.util.EnumSet;
 import java.util.Set;

 import static com.book.ordermanagement.state.OrderStateConstant.*;

@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<String, OrderStateChangeAction> {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;


    @Override
    public void configure(StateMachineStateConfigurer<String, OrderStateChangeAction> states) throws Exception {
        states.withStates().initial( ORDER_WAIT_PAY)// 待支付
                .states(OrderStateConstant.STATES);// 将所有状态配置到状态机中

    }

    @Override
    public void configure(StateMachineTransitionConfigurer<String, OrderStateChangeAction> transitions) throws Exception {
        transitions
                .withExternal()
                .source( ORDER_WAIT_PAY)
                .target(ORDER_WAIT_SEND)
                .event(OrderStateChangeAction.PAY_ORDER)
                .and()
                .withExternal()
                .source( ORDER_WAIT_SEND)
                .target( ORDER_WAIT_RECEIVE)
                .event(OrderStateChangeAction.SEND_ORDER)
                .and()
                .withExternal()
                .source(ORDER_WAIT_RECEIVE)
                .target(ORDER_FINISH)
                .event(OrderStateChangeAction.RECEIVE_ORDER);
    }

    @Bean(name = "stateMachineRedisPersiter")
    public RedisStateMachinePersister<String,OrderStateChangeAction> getRedisPersister(){
        RedisStateMachineContextRepository<String, OrderStateChangeAction> repository = new RedisStateMachineContextRepository<String, OrderStateChangeAction>(redisConnectionFactory);
        RepositoryStateMachinePersist<String, OrderStateChangeAction> persist = new RepositoryStateMachinePersist<>(repository);
        return new RedisStateMachinePersister<>(persist);

    }
}
